﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SystemUpdatesCore.Client;
using SystemUpdatesCore.Server;

namespace SystemUpdatesCore
{
    public class AppUpdate
    {
        public AppUpdate()
        {
            client = new ClientFile();
            server = new ServerVersion();
        }

        public IClient client { get; }
        public ServerVersion server { get; }

        ClientVersionModel clientVersion;




        /// <summary>
        /// 检查更新
        /// </summary>
        /// <param name="clientUrl"></param>
        /// <param name="systemName"></param>
        /// <returns></returns>
        public async Task<bool> IsNew(ClientUrlMode clientUrl, string systemName)
        {
            var clientVer = await GetClientVer(clientUrl);
            var serverVerNum = await GetVersionNum(systemName);

            if (clientVer == null || string.IsNullOrEmpty(clientVer.Version))
            {
                return false;
            }
            if (string.IsNullOrEmpty(serverVerNum))
            {
                return false;
            }

            return serverVerNum == clientVer.Version;
        }



        /// <summary>
        /// 获取本地版本
        /// </summary>
        /// <param name="clientUrl"></param>
        /// <returns></returns>
        public async Task<ClientVersionModel> GetClientVer(ClientUrlMode clientUrl)
        {
            try
            {
                if (clientVersion != null)
                    return clientVersion;

                var ver = await client.GetVersion(clientUrl);
                clientVersion = ver;
                return ver;
            }
            catch
            {
                return null;
            }
        }

        /// <summary>
        /// 获取服务器版本
        /// </summary>
        /// <param name="systemName"></param>
        /// <returns></returns>
        public async Task<string> GetVersionNum(string systemName)
        {
            try
            {
                return await server.GetVersionNum(systemName);
            }
            catch (Exception)
            {
                return null;
            }
        }

    }
}
